import React, { useState, useEffect } from 'react';

// 计数器自定义HOOK，initialCount 是初始值
function useCounter(initialCount) {
  const [count, setCount] = useState(initialCount); // 计数
  const [pause, setPause] = useState(false); // 是否暂停

  useEffect(() => {
    const timer = setTimeout(() => {
      !pause && setCount(count + 1); // 如果没有暂停，计数+1
    }, 1000);
    return () => clearTimeout(timer); // 组件销毁前和更新前，清理 timer
  }, [count, pause]); // 所有要用的变量需要放到监听依赖列表

  // 重置计数
  const reset = () => setCount(initialCount);

  // 暂停或启动
  const toggle = () => setPause(!pause);

  return [count, reset, toggle]; // 把需要的暴露出去（API）
}

function TimerHook() {
  const [count1, resetCount1, toggle] = useCounter(10);
  const [count2] = useCounter(100);
  return (
    <div>
      TimerHook
      <br />
      <strong>{count1}</strong>
      <button onClick={resetCount1}>Reset</button>
      <button onClick={toggle}>Pause/Start</button>
      <br />
      <strong>{count2}</strong>
    </div>
  );
}

export default TimerHook;
